<template>
  <div>

    <div class="noteHint">
      <p class="content">我们已发送验证码，请</p>
      <div class="contents">
        输入 <span style="font-size: 17px;color:#000000">{{ this.date.phoneNumber }}</span>收到的短信
      </div>
      <p class="content">验证码</p>
    </div>
    <!-- 验证码 -->
    <div class="verify">
      <span>验证码</span>
      <input type='tel' v-model="verify" maxlength="6" placeholder="请输入验证码">
      <span v-show="showm" class="gain" @click="code">获取验证码</span>
      <span v-show="!showm" class="gain" style="color: #999999;">重新发送({{ count }})</span>
    </div>
    <!-- 确定 -->
    <div class="errors" v-show="transfer">
      您输入的验证码不正确，请重新输入。
    </div>
    <div :class="verify.length==6?'btns':'addbut'" @click="addres">
      确定
    </div>
  </div>
</template>
<script>
let u = navigator.userAgent;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
import Vue from 'vue';
import {Toast} from 'vant';

Vue.use(Toast);
export default {
  data() {
    return {
      transfer: false,
      showm: true,
      count: '',//验证码获取倒计时
      date: '',
      domain: '',//域名
      repPathUrl: '',//广告域名
      Authorization: '',//Basic c3dvcmQ6c3dvcmRfc2VjcmV0
      tokenPassword: '',//广告密码
      tokenName: '',//广告名字
      hubBaseUrl: '',//hub平台
      facility: '',//唯一标识
      clientType: '',//手机类型
      smsSeq: '',//短信
      verify: '',//验证码
      cardChkNo: '',
      cardChkFlag: '',
      userinfolist: '',//登录信息
      token: '',//token获取
      open: 1
    }
  },
  computed: {
    pitch: function () {
      if (this.ycardvalue && this.newCardValue && this.IdNumder && this.phoneNumber && this.Passwords) {
        return true
      } else {
        return false
      }
    },
  },
  mounted() {
    console.log("获取", JSON.parse(this.$route.query.data))
    this.date = JSON.parse(this.$route.query.data)
    let open = sessionStorage.getItem('open') ? sessionStorage.getItem('open') : this.$route.query.id
    console.log("存储数据", open, sessionStorage.getItem('open'), this.$route.query.id)
    sessionStorage.setItem('open', '2')
    setTimeout(() => {
      // 获取域名
      BmacJSBridge.call('obtainClientBaseUrl', seft => {
        this.domain = seft.pay3BaseUrl
        this.repPathUrl = seft.adBaseUrl
        this.Authorization = seft.Authorization
        this.tokenPassword = seft.adTokenPassword
        this.tokenName = seft.adTokenName
        this.hubBaseUrl = seft.hubBaseUrl
        // 获取手机型号
        if (isAndroid) {
          this.clientType = "Android";
        } else {
          this.clientType = "ios";
        }
        // 获取登录信息
        BmacJSBridge.call('getAPDataStorage', {
          type: "common",
          business: "userInfoGrid",
          key: "userInfo",
        }, (result) => {
          if (result.error == '11' && result.errorMessage == '未找到该数据') {
            // this.loginopen=false
            // this.userinfolist={}
          } else {
            console.log("获取登录信息1", JSON.parse(result.data).data)
            // this.loginopen=true
            this.userinfolist = JSON.parse(result.data).data
            this.token = this.userinfolist.token_type + " " + this.userinfolist.access_token

          }
        })
        // 获取手机唯一标识
        BmacJSBridge.call('getBasicInfo', (data) => {//获取手机唯一标识等
          console.log("获取手机唯一表示", data)
          this.facility = data.deviceData
          if (open == '1') {
            this.code()
          }

        });


      })
    }, 300)
  },
  methods: {
   async addres() {
      let embedding = {
        eventID: "addres",
        extra: {
          name: "确认企业员工卡换卡"
        },
      };
      BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
      })
      //  this.$router.push({path:'/results'})
      console.log(this.smsSeq)
      let initInfo = await  this.getAPPConfigureInfo();
      let basicInfo = await  this.getBasicInfo()
      if (this.verify.length == 6) {
        var body = null;
        if (this.date.newCardValue.length == 16 || this.date.newCardValue.length == 19) {//判断新卡号长度 确定卡校验标识
          this.cardChkFlag = "0"
          body = JSON.stringify({
            idType: '1',                          //证件类型
            msgVerifyCode: this.verify,            //短信验证码verify
            channelType: 'MOB',                    //渠道类型
            merId: '003070000001',                 //商户号
            clientType: this.clientType,           //客户端类型weex.config.env.osName //this.clientType
            passWord: this.date.Passwords,            //支付密码
            cardChkFlag: this.cardChkFlag,         //有无卡校验位
            newCardNo: this.date.newCardValue,           //新卡号
            customerId: this.userinfolist.customerId,    //客户号
            identifyId: this.date.IdNumder,          //证件号
            smsBusiType: '6',                      //短信业务类型
            smsSeq: this.smsSeq,                   //短信流水号
            srandNum: this.date.random,               //加密随机数
            channelId: "75111023",                 //渠道号75111023
            encFlag: '1',                          //加密标识2
            oldCardNo: this.date.ycardvalue,            //原卡号
            mobileNo: this.date.phoneNumber,            //手机号
            logonId: this.userinfolist.logonIds,        //登陆名
            version: initInfo.encryptControl == '01' ? basicInfo.version: '',
          });
        } else if (this.date.newCardValue.length == 20 || this.date.newCardValue.length == 23) {
          this.cardChkFlag = "1"
          this.cardChkNo = this.date.newCardValue.substring(this.date.newCardValue.length - 4, this.date.newCardValue.length)
          body = JSON.stringify({
            idType: '1',                           //证件类型
            msgVerifyCode: this.verify,            //短信验证码verify
            channelType: 'MOB',                    //渠道类型
            merId: '003070000001',                 //商户号
            clientType: this.clientType,           //客户端类型weex.config.env.osName //this.clientType
            passWord: this.date.Passwords,            //支付密码
            cardChkFlag: this.cardChkFlag,         //有无卡校验位
            cardChkNo: this.cardChkNo,             //卡校验位数值
            newCardNo: this.date.newCardValue,           //新卡号
            customerId: this.userinfolist.customerId,    //客户号
            identifyId: this.date.IdNumder,          //证件号
            smsBusiType: '6',                      //短信业务类型
            smsSeq: this.smsSeq,                   //短信流水号
            srandNum: this.date.random,               //加密随机数
            channelId: "75111023",                 //渠道号
            encFlag: '2',                          //加密标识
            oldCardNo: this.date.ycardvalue,            //原卡号
            mobileNo: this.date.phoneNumber,            //手机号
            logonId: this.userinfolist.logonIds,        //登陆名
            version: initInfo.encryptControl == '01' ? basicInfo.version : '',
          });
        }
        console.log("确定后参数", JSON.parse(body))
        this.transfer = false;
        if(initInfo.encryptControl == '01'){
          BmacJSBridge.call("encryptDataWithGuomi", JSON.parse(body), datay => {
            this.$ajax({
              method: "post",
              url: this.domain + '/wolf-customer/customer/qyzhhk',
              data: {
                data:datay.encryptedData,
                deviceId:basicInfo.imei,
                channelId:'BMAC',
                authenticator:'SM4',
              },
              headers: {
                'Content-Type': 'application/json',
                'Authorization': this.Authorization,
                'wolf-auth': this.token
              },
            }).then(res => {
              BmacJSBridge.call("decryptDataWithGuomi", {decryptParam: res.data.data}, (databut) => {
                let starts = JSON.parse(decodeURIComponent(databut.encryptedData));
                console.log("确定换卡返回", starts)
                if (starts.data.retCode == '6317') {
                  this.transfer = true;
                  return

                } else if (starts.data.retCode == '9001') {
                  Toast("网络开小差");
                  return
                } else {
                  this.$router.push({path: '/results', query: {id: JSON.stringify(starts.data), No: 1}})

                }

              })


            }).catch(error => {
              if (error.response) {
                BmacJSBridge.call("decryptDataWithGuomi", {decryptParam: error.response.data},
                  databut => {
                    let request = JSON.parse(decodeURIComponent(databut.encryptedData));
                    // console.log("错误", request);
                    if (request.code == 401) {
                      var text = request.msg || request.message;
                      Toast(text);
                      setTimeout(() => {
                        BmacJSBridge.call('startApp', {
                          appId: '00000060',
                          type: 1,
                          closeCurrentApp: true
                        }, function (result) {
                          // noop
                        });
                      }, 2000);
                    }
                  }
                );
              } else {
                this.ticketListopen = false;
                Toast("网络开小差");
              }
            })
          })
        }else {
          BmacJSBridge.call("encryptDataWithRSA3", JSON.parse(body), datay => {
            this.$ajax({
              method: "post",
              url: this.domain + '/wolf-customer/customer/qyzhhk',
              data: datay.encryptedData,
              headers: {
                'Content-Type': 'application/json',
                'Authorization': this.Authorization,
                'wolf-auth': this.token
              },
            }).then(res => {
              BmacJSBridge.call("decryptDataWithRSA3", {decryptParam: res.data}, (databut) => {
                let starts = databut.encryptedData;
                console.log("确定换卡返回", starts)
                if (starts.data.retCode == '6317') {
                  this.transfer = true;
                  return

                } else if (starts.data.retCode == '9001') {
                  Toast("网络开小差");
                  return
                } else {
                  this.$router.push({path: '/results', query: {id: JSON.stringify(starts.data), No: 1}})

                }

              })


            }).catch(error => {
              if (error.response) {
                BmacJSBridge.call("decryptDataWithRSA3", {decryptParam: error.response.data},
                  databut => {
                    let request = databut.encryptedData;
                    // console.log("错误", request);
                    if (request.code == 401) {
                      var text = request.msg || request.message;
                      Toast(text);
                      setTimeout(() => {
                        BmacJSBridge.call('startApp', {
                          appId: '00000060',
                          type: 1,
                          closeCurrentApp: true
                        }, function (result) {
                          // noop
                        });
                      }, 2000);
                    }
                  }
                );
              } else {
                this.ticketListopen = false;
                Toast("网络开小差");
              }
            })
          })
        }

      }
    },
    code() {//获取验证码
      // if(/^1(3|4|5|7|8)\d{9}$/.test(this.phoneValue)){
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.showm = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.showm = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000)
      }
      this.getCode()//验证码接口
      //   }else{
      //     // this.showToast("请输入正确手机号")
      // }
    },
    getCode() {
      let getCodeData = {
        jpushId: this.facility.jpushId,//极光
        mobileNo: this.date.phoneNumber,  //手机号this.cardNumber3
        smsBusiType: '6',            //验证验证码类型
        channelCode: '3103',         //渠道码
        channelType: 'MOB',          //渠道类型
        merId: '003070000001',       //商户号
        clientType: this.clientType,                 //客户端类型weex.config.env.osName //this.clientType
        imei: this.facility.imei, //手机唯一标识'96BC8B92-2911-4643-8CA5-8FA65A96F769'
        channelId: "75111023",
      }
      console.log("短信下发参数", getCodeData)


      BmacJSBridge.call("encryptDataWithRSA3", getCodeData, datay => {
        this.$ajax({
          method: "post",
          url: this.domain + '/wolf-commonbusi/common/verifycode/get',
          data: datay.encryptedData,
          headers: {
            'Content-Type': 'application/json',
            'Authorization': this.Authorization,
          },
        }).then(res => {
          BmacJSBridge.call("decryptDataWithRSA3", {decryptParam: res.data}, (databut) => {
            let starts = databut.encryptedData;
            console.log("1短信1下发的结果", starts)
            // Toast(starts.data.retMsg)
            if (starts.data.retCode == '0000') {
              this.smsSeq = starts.data.smsSeq
            } else {
              Toast(starts.data.retMsg)
            }

          })


        })
          .catch(err => {
            console.log(err)
          })
      })
    },
    /**
     * 获取引用初始化接口参数
     */
    getAPPConfigureInfo() {
      return new Promise((resolve, reject) => {
        BmacJSBridge.call("getAPPConfigureInfo", (data) => {
          resolve(data)
        })
      })
    },

    /**
     * 获取基本信息
     */
    getBasicInfo() {
      return new Promise((resolve, reject) => {
        BmacJSBridge.call("getBasicInfo", {}, (data) => {
          let phoneData = data.deviceData;
          resolve(phoneData)
        });
      })

    },
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../common/stylus/mixin.styl';
.noteHint {
  height: 3.2rem;
  background-color: #ffffff;
  display flex;
  flex-direction column;
  justify-content: center;
  align-items: center;

}

.content {
  text-align: center;
  font-size: 17px;
  color: #999999;
  line-height 26px;
}

.contents {
  font-size: 17px;
  line-height 20px;
  flex-direction: row;
  color: #999999;
  align-items: center;
}

.verify {
  display flex;
  align-items center;
  height 1.04rem;
  font-size 14px;
  background #ffffff;
  margin-top 12px;
  padding: 0 0.32rem;

  input {
    flex: 1;
    margin-left: 0.6rem;

  }

  .gain {
    flex 1;
    text-align center;
    font-size 0.28rem;
    color: #008DEE;
  }
}

.addbut {
  font-size: 14px;
  color: #FFFFFF;
  background: #cccccc;
  border-radius: 4px;
  height 0.88rem;
  margin: 0.32rem;
  text-align center;
  line-height 0.88rem;
}

.btns {
  background: #008DEE;
  font-size: 14px;
  color: #FFFFFF;

  border-radius: 4px;
  height 0.88rem;
  margin: 0.32rem;
  text-align center;
  line-height 0.88rem;
}

.errors {
  margin 0.32rem 0.32rem 0 0.32rem;
  font-size: 12px;
  color: #FF4D4D;
}
</style>
